<?php
namespace app\common\model;

use think\model\concern\SoftDelete;

class ArticleCateModel extends BaseModel
{
    use SoftDelete;

    protected $table='article_cate';

    /**
     * 获取商品数据
     * @param array $input_data 请求内容
     * @throws
     * @return \think\Collection
     * */
    public static function getAllCate(array $input_data=[])
    {

        $keyword = trim($input_data['keyword']??'');
        $where = [];
        $where[] = ['pid','=',0];
        !empty($keyword) && $where[] = ['name','like','%'.$keyword.'%'];


        if(isset($input_data['status'])){
            $where[] = ['status','=',$input_data['status']];
        }


        return self::with(['linkChild'])->where($where)->order('sort asc')->select();

    }

    public static function getSelectList(array $input_data = [] )
    {
        $where = [];
        if(isset($input_data['status'])){
            $where[] = ['status','=',$input_data['status']];
        }
        $list = [];
        self::with(['linkChild'=>function($query)use($where){
            $query->where($where);
        }])->where(['pid'=>0])->where($where)->select()->each(function($item,$index)use(&$list){
            $info = $item->apiFullInfo();
            $info['child_list'] = [];
            $linkChild = $item->getRelation('linkChild');
            $child_list = [];
            if(!empty($linkChild)){
                foreach ($linkChild as $vo){
                    array_push($child_list,$vo->apiFullInfo());
                }
            }
            $info['child_list'] = $child_list;
            array_push($list,$info);
        });
        return $list;
    }

    public static function handleSaveData(array $input_data = [])
    {
        if(empty($input_data['name'])) throw new \Exception('请输入名字');
        (new self())->actionAdd($input_data);
    }


    public function apiFullInfo()
    {

        return array_merge($this->apiNormalInfo(),[
            'update_time' => $this['update_time'],

            'status'=>(string)$this['status'],
            'status_name'=>self::getPropInfo('fields_status',$this['status'],'name'),
        ]);
    }

    public function apiNormalInfo()
    {
        return [
            'id'=>$this->getAttr('id'),
            'pid'=>$this->getAttr('pid'),
            'name'=>$this->getAttr('name'),
            'img'=>$this->getAttr('img'),
            'sort'=>$this->getAttr('sort'),
        ];
    }


    public function linkChild()
    {
        return $this->hasMany(ArticleCateModel::class,'pid')->order('sort asc');
    }
}